const express = require('express');
const router = express.Router();
const md5=require('md5')
const Novel=require('../../../express-backend/models/Novel')
const User = require('../../../express-backend/models/User');
const Competition=require('../models/Competition')
const jwt=require('jsonwebtoken')
const path = require('path');
const authenticateToken =require('../middlewares/authenticateToken');


//获取待审核作品列表
router.get('/review/list', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    
    // 按条件查询
    const novels = await Novel.find({state:"待审核"})
      .sort({ createdAt: -1 }) // 仅保留一个排序（原代码两个sort，后一个覆盖前一个）
      .select('-__v');
    
    res.json({
      code: '0000',
      msg: '获取待审核列表成功',
      data: novels.map(novel => ({
        id: novel._id,
        title: novel.title,
        cate_name: novel.cate_name,
        state: novel.state,
        pub_date: novel.pub_date,
        cover: novel.cover,
        content: novel.content,
        word_count: novel.word_count, // 新增
        chapter_count: novel.chapter_count, // 新增
        last_update: novel.last_update // 新增
      }))
    });
  } catch (err) {
    res.json({ code: '2001', msg: '获取列表失败: ' + err.message, data: null });
  }
});

//审核作品接口
router.post('/review/novel', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    const { novelId, action } = req.body;
    // 参数校验
    if (!novelId) {
      return res.json({
        code: '2011',
        msg: '小说ID不能为空',
        data: null
      });
    }
    if (!['通过', '拒绝'].includes(action)) {
      return res.json({
        code: '2012',
        msg: '无效的操作类型',
        data: null
      });
    }
    // 查找小说
    const novel = await Novel.findById(novelId);
    if (!novel) {
        return res.json({
            code: '2013',
            msg: '小说不存在',
            data: null
        });
    }
    // 更新小说状态
    novel.state = action === '通过' ? '连载' : '下架';
    await novel.save();
    res.json({
      code: '0000',
      msg: `小说审核${action}成功`,
      data: null
    });
  }
    catch (err) {
    res.json({
      code: '2001',
      msg: '审核操作失败: ' + err.message,
        data: null
    });
  }
});

//获取待审核作者列表
router.get('/review/authorlist', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    // 按条件查询
    const authors = await User.find({contractStatus:"待审核"})
      .sort({ createdAt: -1 }) // 仅保留一个排序（原代码两个sort，后一个覆盖前一个）
        .select('-__v');
    res.json({
      code: '0000',
      msg: '获取待审核作者列表成功',
        data: authors.map(author => ({
        id: author._id,
        username: author.username,
        nickname: author.nickname,
        avatar: author.avatar,
        contractStatus: author.contractStatus,
        bio: author.bio // 新增
      }))
    });
  }
    catch (err) {   
    res.json({ code: '2001', msg: '获取列表失败: ' + err.message, data: null });
  }
});

//审核作者签约
router.post('/review/author', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    const { authorId, action } = req.body;
    // 参数校验
    if (!authorId) {
        return res.json({
            code: '2014',
            msg: '作者ID不能为空',
            data: null
        });
    }
    if (!['通过', '拒绝'].includes(action)) {
        return res.json({
            code: '2015',
            msg: '无效的操作类型',  
            data: null
        });
    }
    const author = await User.findById(authorId);
    if (!author) {
        return res.json({
            code: '2016',
            msg: '作者不存在',
            data: null
        });
    }
    // 更新作者签约状态
    author.contractStatus = action === '通过' ? '签约ing' : null;
    await author.save();
    res.json({
      code: '0000',
      msg: `作者签约审核${action}成功`,
      data: null
    });
  } catch (err) {
    res.json({
      code: '2001',
      msg: '审核操作失败: ' + err.message,
        data: null
    });
  }
});

//获取待审核征文比赛参赛作品列表
router.get('/review/competitionlist', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;

    // 按条件查询
    const novels = await Novel.find({contestStatus:"待审核"})
      .sort({ createdAt: -1 }) // 仅保留一个排序（原代码两个sort，后一个覆盖前一个）
      .select('-__v');
    res.json({
      code: '0000',
      msg: '获取待审核征文比赛参赛作品列表成功',
        data: novels.map(novel => ({
        id: novel._id,
        title: novel.title,
        cate_name: novel.cate_name,
        state: novel.state,
        pub_date: novel.pub_date,
        cover: novel.cover,
        content: novel.content,
        word_count: novel.word_count, // 新增
        chapter_count: novel.chapter_count, // 新增
        last_update: novel.last_update // 新增
      }))
    });
  } catch (err) {
    res.json({ code: '2001', msg: '获取列表失败: ' + err.message, data: null });
  }
});

//审核征文比赛参赛作品
router.post('/review/competition', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    const { contestId, action } = req.body;
    // 参数校验
    if (!contestId) {
        return res.json({
            code: '2017',
            msg: '参赛作品ID不能为空',
            data: null
        });
    }
    if (!['通过', '拒绝'].includes(action)) {
        return res.json({
            code: '2018',
            msg: '无效的操作类型',  
            data: null
        });
    }
    const novel = await Novel.findById(contestId);
    if (!novel) {
        return res.json({
            code: '2019',
            msg: '参赛作品不存在',
            data: null
        });
    }
    // 更新参赛作品状态
    novel.contestStatus = action === '通过' ? '征文ing' : null;
    await novel.save();
    res.json({
      code: '0000',
      msg: `参赛作品审核${action}成功`,
      data: null
    });
  } catch (err) {
    res.json({
      code: '2001',
      msg: '审核操作失败: ' + err.message,  
        data: null
    });
  }
});

//其他：发布征文
router.post('/review/publishcompetition', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    const { title, content } = req.body;
    // 参数校验
    if (!title) {
        return res.json({
            code: '2020',
            msg: '征文标题不能为空',
            data: null
        });
    }
    if (!content) {
        return res.json({
            code: '2021',
            msg: '征文内容不能为空',
            data: null
        });
    }
    // 创建征文作品
    const newCompetition = new Competition({
      title,
      content,
    });
    await newCompetition.save();
    res.json({
        code: '0000',
        msg: '征文发布成功',
        data: {
            id: newCompetition._id
        }
    });
  } catch (err) {
    res.json({
      code: '2001',
      msg: '发布征文失败: ' + err.message,
        data: null
    });
  }
});

module.exports = router;
